package com.testing.vip13login.controller;

import com.testing.vip13login.mapper.UserMapper;
import com.testing.vip13login.model.Result;
import com.testing.vip13login.model.User;
import com.testing.vip13login.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Classname UserController
 * @Description 类型说明
 * @Date 2022/9/26 22:20
 * @Created by 特斯汀Roy
 */
@RestController
@RequestMapping("user")
@Api(tags = "用户操作类接口",description = "用户操作登录登出、注册")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    @PostMapping("/login")
    @ApiOperation(value="登录")
    public Result login(@ApiParam(value = "用户名",required = true) @RequestParam String username,
                        @ApiParam(value = "密码",required = true) @RequestParam String password,
                        HttpServletRequest request, HttpServletResponse response) {
        //获取session
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        System.out.println("登录的时候，sessionid是" + sessionId);
        //设置session的有效周期（生命周期）为10秒
        session.setMaxInactiveInterval(120);
        //从session中获取存储的信息。
        Object guest = session.getAttribute("guest");
        System.out.println("当前的用户是" + guest);

        //Cookie获取
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            System.out.println("没有cookie");
        }else{
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + "的值是" + cookie.getValue() + "它的生命周期是" + cookie.getMaxAge());
            }
        }



        //如果有人登录了，session中的 属性guest就不是null
        if (guest != null) {
            //已经有人登陆了
            if (guest.toString().equals(username)) {
                return new Result(-4, "不能再次登录", "您已经登录过了");
            } else {
                return new Result(-5, "不能再次登录", "已经有另一个用户" + guest + "登录了");
            }
        }
        //登录成功的时候让session中记录用户的信息
        Result login = userService.login(username, password);
        //判断登录是否成功
        if (login.getCode() == 1) {
            //登录成功的时候，session记录了用户的信息
            session.setAttribute("guest", username);
            //重新生成一个JSESSIONID的cookie,因为服务端默认用这个cookie来查找session
            Cookie jid=new Cookie("JSESSIONID",sessionId);
            //建议和session生命周期保持一致
            jid.setMaxAge(120);
            //设置这个cookie也是在根路径下有效的，避免生成两个不同的cookie
            jid.setPath("/");
            //在返回信息中，将cookie添加进去，随之一起返回给客户端。
            response.addCookie(jid);
        }
        System.out.println("---------------本次调用结束--------------------");
        return login;
    }

    @GetMapping("/logout")
    @ApiOperation(value = "注销",notes = "完成注销操作")
    public Result logout(HttpServletRequest request) {
        //清空session的存储
        HttpSession session = request.getSession();
        //唯一标识本次会话的id
        String sessionId = session.getId();
        System.out.println("登出的时候sessionId是" + sessionId);
        Object guest = session.getAttribute("guest");
        System.out.println("登出的时候，session记录的用户是" + guest);
        //让session失效。
        session.invalidate();
        return new Result(1, "登出成功", "已经完成登出了，欢迎下次再来");
    }

    @GetMapping("/getUser")
    @ApiOperation(value="获取用户信息",notes="获取用户信息")
    public Result getUserInfo(HttpServletRequest request){
        //获取session中存的已经登录的用户的信息。
        Object guest = request.getSession().getAttribute("guest");
        if (guest==null){
            return new Result(-1,"你还没有登录，不能查询用户信息","未登录不能查询");
        }
        return userService.queryByUserName(guest.toString());
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册用户")
    public Result register(@ApiParam(value = "请求用户json") @RequestBody User user){
        return userService.register(user.getUsername(),user.getPassword(),user.getNickname(),user.getDescribe());
    }

    @DeleteMapping("/delete/{user}")
    public Result deleteUser(@PathVariable String user){
        return userService.deleteUserByName(user);
    }

    @GetMapping("/all")
    public List<User> getAllUsers(){
        System.out.println("被调用了");
        return  userMapper.queryAllUsers();
    }


}
